package com.smzh.service;

import com.smzh.bean.ListNode;
/**
 * 链表交换，相邻两个节点交换
 * 例如：1->2->3->4 交换后  2->1->4->3
 * @author jun
 *
 */
public class ChangeLinkedList {

	public ListNode swapPairs(ListNode head) {
		if (head == null || head.next == null)
			return head;
		ListNode result = new ListNode(0);
		ListNode p = result;
		ListNode q = head;
		while (q != null && q.next != null) {
			ListNode temp = q.next.next;
			p.next = q.next;
			p=p.next;
			p.next = q;
			p = p.next;
			p.next = null;
			q = temp;
		}
		if (q != null)
			p.next = q;
		return result.next;
	}

	public static void main(String[] args) {
		ListNode head = new ListNode(1);
		ListNode s = new ListNode(2);
		ListNode t = new ListNode(3);
		ListNode f = new ListNode(4);
		head.next = s;
		s.next = t;
		t.next = f;
		ChangeLinkedList changeLinkedList = new ChangeLinkedList();
		System.out.println(changeLinkedList.swapPairs(head));

	}
}
